package com.chapter03;

import com.bdqn.util.JDBCUtils;
import com.pojo.Grade;
import com.pojo.Student;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Test09_TestQuery {
    public static void main(String[] args) throws ClassNotFoundException, SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException {
//        List<Grade> list = Test09_TestQuery.<Grade>query(
//                Grade.class,
//                "SELECT gradeId,gradeName FROM grade;"
//        );
//        for (Grade grade : list) {
//            System.out.println(grade);
//        }

        List<Student> list = Test09_TestQuery.<Student>query(
                Student.class,
                "SELECT studentNo,loginPwd,studentName,sex,gradeId,phone,address,bornDate,email FROM student;"
        );
        for (Student student : list) {
            System.out.println(student);
        }
    }

    public static <T> List<T> query(Class<T> clazz, String sql, Object... objs) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        List<T> list = new ArrayList<>();

        Connection connection = JDBCUtils.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        ResultSetMetaData rsmd = resultSet.getMetaData();
        int columnCount = rsmd.getColumnCount();

        while (resultSet.next()) {

            // 通过反射的方式创建了一个grade对象
            T t = clazz.newInstance();

            for (int i = 0; i < columnCount; i++) {
                // 拿到每一列的值
                Object objValue = resultSet.getObject(i + 1);
                // 可以拿到列的名称
                String columnLabel = rsmd.getColumnLabel(i + 1);

                // 拿到一个字段
                Field field = clazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                field.set(t, objValue);
            }
            list.add(t);
        }

        resultSet.close();
        preparedStatement.close();
        connection.close();

        return list;
    }
}
